package com.unina.is2.astafantaunina.activity;

import com.unina.is2.astafantaunina.R;
import com.unina.is2.astafantaunina.chat.ChatGruppo;
import com.unina.is2.astafantaunina.chat.PresenceListener;
import com.unina.is2.astafantaunina.database.Database;
import com.unina.is2.astafantaunina.service.ServiceOpenfire;
import com.unina.is2.astafantaunina.utility.ButtonState;
import com.unina.is2.astafantaunina.utility.EliminaCalciatoreTask;
import com.unina.is2.astafantaunina.utility.VisibilityManager;

import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.ToggleButton;

public class LegheActivity extends ActionBarActivity {
	
	private final static String MY_PREFERENCES = "UtenteAstaFantaunina";
	
	private static Context context;
	
	public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
	
	private static TableLayout table;

	@Override
	protected void onPause() {
	    VisibilityManager.setIsVisible(false);
	    VisibilityManager.setContext(null);
	    unregisterReceiver(abilitaButtonLega);
	    super.onPause();
	}
	
	
	@Override
	protected void onResume() {
	    super.onResume();
	    
	    registerReceiver(abilitaButtonLega, new IntentFilter("ABILITA_BUTTON"));

	    VisibilityManager.setDoveSiamo(0);
	    VisibilityManager.setIsVisible(true);
	    VisibilityManager.setContext(context);
	}
	
	private BroadcastReceiver abilitaButtonLega = new BroadcastReceiver(){

		@Override
		public void onReceive(Context context, Intent intent) {
			
			System.out.println("provo ad abilitare il button");
			
			SharedPreferences sharedPref = getSharedPreferences(MY_PREFERENCES,Context.MODE_PRIVATE);
			int indice = sharedPref.getInt("indice_lega", -1);
		    
			System.out.println("indice lega "+indice);
			
		    TableRow righe= (TableRow) table.getChildAt(indice);
		    
		    Button t = (Button) righe.getChildAt(0);
		    
		    ToggleButton toggle = (ToggleButton) righe.getChildAt(1);
		    
		    toggle.setEnabled(true);
		    
		    t.setEnabled(true);
		    
		    System.out.println("FINE");
			
		}
		
		
		
	};
	
	public static Context getContext(){
		return context;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_leghe);
		context = this;

		Database db = new Database(this);
		db.open();
		db.close();
		
		
		if (savedInstanceState == null) {
			getSupportFragmentManager().beginTransaction()
					.add(R.id.container, new PlaceholderFragment()).commit();
		}
	}
	
	@Override
	public void onBackPressed(){
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    builder.setMessage("Sei sicuro di voler uscire?")
	           .setCancelable(false)
	           .setPositiveButton("SI", new DialogInterface.OnClickListener() {
	               public void onClick(DialogInterface dialog, int id) {
	                    //finish();
	            	   moveTaskToBack(true);
	               }
	           })
	           .setNegativeButton("NO", new DialogInterface.OnClickListener() {
	               public void onClick(DialogInterface dialog, int id) {
	                    dialog.cancel();
	               }
	           });
	    AlertDialog alert = builder.create();
	    alert.show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.leghe, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.activity_leghe,
					container, false);			
			
			return rootView;
		}
		
		
		
		@Override
		public void onViewCreated(View view, Bundle savedInstanceState)
		{
		    // TODO Auto-generated method stub
		    super.onViewCreated(view, savedInstanceState);

		    
		    
		    //Set a linearLayout to add buttons
		    TableLayout tableLayout = new TableLayout(getActivity());
		    // Set the layout full width, full height
		   
		    tableLayout.setOrientation(LinearLayout.VERTICAL); //or VERTICAL
		    
		    SharedPreferences sharedPref = getActivity().getSharedPreferences(MY_PREFERENCES,Context.MODE_PRIVATE);

		    String leghe = sharedPref.getString("leghe", "nessun dato");
		    String amministra = sharedPref.getString("amministratore", "nessun amministratore");
		    
		    String [] split_leghe = leghe.split("-");
		    String [] split_amministra = amministra.split("-");
		    
		    final Button [] button = new Button[split_leghe.length];
		    final ToggleButton [] toggle = new ToggleButton[split_leghe.length];
		    	    	    
		    //Inizializziamo l'oggetto contenente le configurazione dei button e delle caselle di testo
		    ButtonState buttonstate = ButtonState.getButtonState();
		    
		    for (int i=0;i<split_leghe.length;i++){
		    	
		    	//ultima lega selezionata
		    	String lega_scelta = sharedPref.getString("lega_scelta", "nesssuna lega");
		    	
		    	//indice del ciclo for
		    	final int indice = i;
		    	//numero di leghe
		    	final int dim = split_leghe.length;
		    	
		    	final String amministratore=split_amministra[i];
		    	final String lega = split_leghe[i];
		    	
		    	TableRow tr = new TableRow(getActivity());
		    	
		    	button[i] = new Button(getActivity());
		    	
		    	toggle[i] = new ToggleButton(getActivity());
		    	
		    	toggle[i].setOnClickListener(new OnClickListener() {

		    		
		            @Override
		            public void onClick(View arg0) {
		                if(toggle[indice].isChecked()){
		                	//Button is ON

		                	SharedPreferences sharedPref = getActivity().getSharedPreferences(MY_PREFERENCES,Context.MODE_PRIVATE);
		                	SharedPreferences.Editor editor = sharedPref.edit();
		                	//Salviamo la lega selezionata
			                editor.putString("lega_scelta",lega);
			                editor.putInt("indice_lega", indice);
			                editor.commit();
		                	
			                VisibilityManager.setToggle(1);
			                
		                	//button[indice].setEnabled(true);
		                	//disabilitamo gli altri toggle
		                	for (int i=0;i<dim;i++){
		                		if (i!=indice)toggle[i].setEnabled(false);
		                	}
		                	//Avvio del servizio
			                Intent intent = new Intent (context, ServiceOpenfire.class);
				            context.startService(intent);
				            
				          //Amministratore della lega		                 
			                 if (amministratore.equals("1")){           	 
			                	 //diciamo al server di collegarsi ad openfire
				                 new EliminaCalciatoreTask().execute(lega,"OK");	                	 
			                 }	  
		                                
			                 toggle[indice].setEnabled(false);
		                }
		                else{
		                	//Button is OFF
		                	button[indice].setEnabled(false);
		                	ChatGruppo.exitStanza();
		                	
		                	VisibilityManager.setToggle(0);
		                	
		                	SharedPreferences sharedPref = getActivity().getSharedPreferences(MY_PREFERENCES,Context.MODE_PRIVATE);
		            		SharedPreferences.Editor editor = sharedPref.edit();
		            		editor.putString("lega_scelta", "");
		            		editor.commit();
		                	
		                	
		            		//Amministratore della lega		                 
			                 if (amministratore.equals("1")){
			                	 System.out.println("is amministratore");
			                	 //diciamo al server di scollegarsi ad openfire
				                 new EliminaCalciatoreTask().execute(lega,"KO");
			                }
		            		
//		                	//Stop servizio
//		                	Intent intent = new Intent (context, ServiceOpenfire.class);
//			            	context.stopService(intent);
			            	//resettiamo anche la connessione
			            	ChatGruppo.azzeraConnessione();
			            	
			            	PresenceListener.azzeraConnessi();
			            	
		                	//abilitiamo gli altri toggle
		                	for (int i=0;i<dim;i++){
		                		if (i!=indice)toggle[i].setEnabled(true);
		                	}
		                }
		            }
		        });
		    	
			    button[i].setText(split_leghe[i]);
			    //deve essere abilitato solo il bottone relativo alla lega scelta
			    if (lega_scelta.equals("")){
			    	button[i].setEnabled(false);
			    }else if (!split_leghe[i].equals(lega_scelta)) {
			    	//bottone e toggle relativo alle leghe non selezionate
			    	button[i].setEnabled(false);
			    	toggle[i].setEnabled(false);
			    } else{
			    	//bottone relativo alla lega selezionato
			    	button[i].setEnabled(true);
			    	toggle[i].setChecked(true);
			    }
			    
			    //Amministratore della lega		                 
                if (amministratore.equals("1")){           	 
               	 buttonstate.setIsAmministratore(true,i );
               	 //diciamo al server di collegarsi ad openfire                	 
                } else{	                	 	                	 
               	 buttonstate.setIsAmministratore(false,i );
                }
			    
			    try{
			    	button[i].setOnClickListener(new View.OnClickListener() {
			    
		             public void onClick(View v) {     
		            	
//		                 //Amministratore della lega		                 
//		                 if (amministratore.equals("1")){           	 
//		                	 //diciamo al server di collegarsi ad openfire
//			                 new EliminaCalciatoreTask().execute(lega,"OK");	                	 
//		                 }	     
		               
			             //chiamiamo nuova activity
			             Intent intent = new Intent(context, LoggedActivity.class);
			             startActivity(intent);
		               
		             }
		         });
			    }catch(Exception e){
			    	
			    }
			    tr.addView(button[i]);
			    tr.addView(toggle[i]);
			    tableLayout.addView(tr);
		    }
		    	    
		            
		    //... and other views

		    ViewGroup viewGroup = (ViewGroup) view;

		    viewGroup.addView(tableLayout);
		    //viewGroup.addView(tl);
		    
		    table = tableLayout;
		}
	}
	
	

}
